package com.benew.ntt.player.utils

import android.content.Context
import android.net.Uri
import com.benew.ntt.player.SourceType
import com.google.android.exoplayer2.DefaultRenderersFactory
import com.google.android.exoplayer2.RenderersFactory
import java.io.File

object ExoPlayerUtils {

    private fun useExtensionRenderers(): Boolean {
        return true
    }

    fun buildRenderersFactory(
        context: Context, preferExtensionRenderer: Boolean
    ): RenderersFactory {
        val extensionRendererMode =
            if (useExtensionRenderers()) if (preferExtensionRenderer) DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER else DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON else DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF
        return DefaultRenderersFactory(context.applicationContext)
            .setExtensionRendererMode(extensionRendererMode)
    }


    private const val SCHEME_FILE = "file";

    /**
     * 根据不同播放类型数据，转换成Uri
     */
    fun generateUri(url: String, sourceType: Int): Uri {
        return when (sourceType) {
            SourceType.SOURCE_TYPE_ASSETS ->
                Uri.parse("file:///android_asset/${url}")
            SourceType.SOURCE_TYPE_FILE ->
                Uri.fromFile(File(url))
            else ->
                Uri.parse(url)
        }
    }

    fun generateUriByType(url: String, sourceType: Int): Uri {
        return when {
            sourceType == SourceType.SOURCE_TYPE_ASSETS -> {
                Uri.parse("file:///android_asset/${url}")
            }
            FileUtils.isFile(url) -> {
                Uri.fromFile(File(url))
            }
            else -> {
                Uri.parse(url)
            }
        }
    }

    fun generateUri(url: String): Uri {
        return if (FileUtils.isFile(url)) {
            Uri.fromFile(File(url))
        } else {
            Uri.parse(url)
        }
    }

    fun isCacheFile(uri: Uri): Boolean {
        return uri.scheme == SCHEME_FILE
    }

}